package com.pangu.util.rules.model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.model.Summary;
import com.pangu.core.engine.game.model.SummaryPlayer;
import com.pangu.util.ProcessCard;
import com.pangu.web.model.GamePlayway;
import com.pangu.web.model.GameRoom;
import com.pangu.web.model.PlayUserClient;

public class SanGongBoard extends Board implements java.io.Serializable {

	/**
	 * Description:
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public byte[] pollLastHands() {
		return null;
	}

	@Override
	public int calcRatio() {
		return 0;
	}

	@Override
	public TakeCards takeCards(Player player, String playerType, TakeCards current) {
		return null;
	}

	@Override
	public int index(String userid) {
		return 0;
	}

	@Override
	public Summary summary(Board board, GameRoom gameRoom, GamePlayway playway) {
		Summary summary = new Summary(gameRoom.getId(), board.getId(), board.getRatio(),
				board.getRatio() * playway.getScore());
		List<PlayUserClient> players = CacheHelper.getGamePlayerCacheBean().getCacheObject(gameRoom.getId(),
				gameRoom.getOrgi());
		Player[] plays = board.getPlayers();
		SummaryPlayer summaryPlayer = null;// 每个结算用户
		PlayUserClient playUser = null;
		String winnerPlayer = whoIsWinner(plays);
		for (Player player : board.getPlayers()) {
			playUser = getPlayerClient(players, player.getPlayuser());
			summaryPlayer = new SummaryPlayer(player.getPlayuser(), playUser.getUsername(), board.getRatio(),
					board.getRatio() * playway.getScore(), false, player.getPlayuser().equals(board.getBanker()));
			// 匹配赢家
			if (summaryPlayer.getUserid().equals(winnerPlayer)) {
				summaryPlayer.setWin(true);
			}
			summaryPlayer.setCards(player.getCards());
			summary.getPlayers().add(summaryPlayer);

		}
		summary.setGameRoomOver(true); // 有玩家破产，房间解散
		return summary;

		// int dizhuScore = 0 ;
		// boolean dizhuWin = board.getWinner().equals(board.getBanker()) ;
		//
		// List<PlayUserClient> players =
		// CacheHelper.getGamePlayerCacheBean().getCacheObject(gameRoom.getId(),
		// gameRoom.getOrgi()) ;
		//
		// PlayUserClient dizhuPlayerUser = getPlayerClient(players, board.getBanker());
		// int temp = summary.getScore() * (board.getPlayers().length - 1) ;
		// SummaryPlayer dizhuSummaryPlayer = null ;
		// PVAOperatorResult result = null ;
		// boolean gameRoomOver = false ; //解散房价
		//
		// for(Player player : board.getPlayers()){
		// PlayUserClient playUser = getPlayerClient(players, player.getPlayuser());
		// SummaryPlayer summaryPlayer = new SummaryPlayer(player.getPlayuser() ,
		// playUser.getUsername() , board.getRatio() , board.getRatio() *
		// playway.getScore() , false , player.getPlayuser().equals(board.getBanker()))
		// ;
		// /**
		// * 找到对应的玩家结算信息
		// */
		// if(player.getPlayuser().equals(board.getBanker())){
		// dizhuSummaryPlayer = summaryPlayer ;
		// }
		// if(dizhuWin){
		// if(player.getPlayuser().equals(board.getBanker())){
		// summaryPlayer.setWin(true);
		// }else{
		// /**
		// * 扣 农民的 金币 , 扣除金币的时候需要最好做一下金币的校验，例如：签名验证是否由系统修改的 金币余额，并记录金币扣除的日志，用于账号账单信息
		// */
		// if(playUser.getGoldcoins() <= summaryPlayer.getScore()){
		// summaryPlayer.setScore(playUser.getGoldcoins());//还有多少，扣你多少
		// summaryPlayer.setGameover(true); //金币不够了，破产，重新充值或领取奖励恢复状态
		// gameRoomOver = true ;
		// }
		// dizhuScore = dizhuScore + summaryPlayer.getScore() ;
		// result = PvaTools.getGoldCoins().consume(playUser ,
		// BMDataContext.PVAConsumeActionEnum.LOST.toString(), summaryPlayer.getScore())
		// ;
		// summaryPlayer.setBalance(result.getBalance());
		// }
		// }else{ //地主输了
		// if(!player.getPlayuser().equals(board.getBanker())){
		// summaryPlayer.setWin(true);
		// if(dizhuPlayerUser.getGoldcoins() < temp){ //金币不够扣
		// summaryPlayer.setScore(dizhuPlayerUser.getGoldcoins() /
		// (board.getPlayers().length - 1));
		// gameRoomOver = true ;
		// }
		// dizhuScore = dizhuScore + summaryPlayer.getScore() ;
		//
		// /**
		// * 应该共用一个 扣除个人虚拟资产的 全局对象，用于处理个人虚拟资产
		// */
		// result = PvaTools.getGoldCoins().income(playUser,
		// BMDataContext.PVAInComeActionEnum.WIN.toString(), summaryPlayer.getScore()) ;
		// summaryPlayer.setBalance(result.getBalance());
		// }
		// }
		// summaryPlayer.setCards(player.getCards()); //未出完的牌
		// summary.getPlayers().add(summaryPlayer) ;
		// }
		// if(dizhuSummaryPlayer!=null){
		// dizhuSummaryPlayer.setScore(dizhuScore);
		// if(dizhuWin){
		// result = PvaTools.getGoldCoins().income(dizhuPlayerUser,
		// BMDataContext.PVAInComeActionEnum.WIN.toString(), dizhuScore) ;
		// }else{
		// result = PvaTools.getGoldCoins().consume(dizhuPlayerUser,
		// BMDataContext.PVAConsumeActionEnum.LOST.toString(), dizhuScore) ;
		// }
		// dizhuSummaryPlayer.setBalance(result.getBalance());
		// }
		// summary.setGameRoomOver(gameRoomOver); //有玩家破产，房间解散
		// /**
		// * 上面的 Player的 金币变更需要保持 数据库的日志记录 , 机器人的 金币扣完了就出局了
		// */
		// return summary;
	}

	/**
	 * 
	 * Description: 谁是赢家
	 * 
	 * @author abo
	 * @date 2018年3月28日
	 * @param plays
	 * @return
	 */
	private String whoIsWinner(Player[] plays) {
		Player p = null;
		Map<String, Object> map = null;
		//缓存前一个对象
		Map<String, Object> prePersionMap = null;
		for (int i = 0; i < plays.length; i++) {
			p = plays[i];
			map = new HashMap<String, Object>();
			map.put("playId", p.getPlayuser());
			byte[] cards = p.getCards();
			int playerCount = 0;
			String tempCardStr = "";
			for (int j = 0; j < cards.length; j++) {
				int cardNum = ProcessCard.byteCardToInt(cards[j]);
				tempCardStr+=cardNum+",";
				map.put("cardNum" + j, cardNum);
				if (cardNum >= 10) {
					cardNum = 0;
				}
				playerCount += cardNum;
			}
			System.out.println(p.getPlayuser() + "======" + tempCardStr);
			//根据牌去匹配牌的类型，爆玖，炸弹，三公，点数
			int cardType = ProcessCard.parseSangongCartTpye(cards);
			// 判断牌型
			map.put("cardType", cardType);
			System.out.println(p.getPlayuser() + "的点数为：" + playerCount % 10 + ";花色为：" + cardType);
			map.put("point", playerCount % 10);
			// 第一次先放入map，然后中断循环
			if (prePersionMap == null) {
				prePersionMap = map;
				continue;
			}
			// 如果是爆玖那么就中断循环，他就是最大赢家
			if (cardType == 4) {
				prePersionMap = map;
				break;
			}
			if (prePersionMap != null) {
				int prePersonCardType = (int) prePersionMap.get("cardType");
				// 1、先比较牌型，如果后者大于前者，那么就保留后者
				if (cardType > prePersonCardType) {
					prePersionMap = map;
				}
				// 2、如果牌型一样，那么就
				if (cardType == prePersonCardType) {
					// 如果都是炸弹
					if (cardType == 3) {
						// 第一张牌大的就是赢家
						if (Integer.parseInt(map.get("cardNum0").toString()) > Integer
								.parseInt(prePersionMap.get("cardNum0").toString())) {
							prePersionMap = map;
						}
					}
					// 如果都是三公
					if (cardType == 2) {
						for (int w = 0; w < 3; w++) {
							// 第一张牌大的就是赢家
							if (Integer.parseInt(map.get("cardNum" + w).toString()) > Integer
									.parseInt(prePersionMap.get("cardNum" + w).toString())) {
								prePersionMap = map;
								break;
							}
						}
					}
					// 如果都是点数
					if (cardType == 1) {
						// 先比点数，点数大就是赢家
						if (Integer.parseInt(map.get("point").toString()) > Integer
								.parseInt(prePersionMap.get("point").toString())) {
							prePersionMap = map;
							continue;
						}
						// 如果点数一样，那么就从第一张牌开始比
						if (Integer.parseInt(map.get("point").toString()) == Integer
								.parseInt(prePersionMap.get("point").toString())) {
							int current = Integer.parseInt(map.get("cardNum0").toString()
									+ map.get("cardNum1").toString() + map.get("cardNum2").toString());
							int pre = Integer.parseInt(
									prePersionMap.get("cardNum0").toString() + prePersionMap.get("cardNum1").toString()
											+ prePersionMap.get("cardNum2").toString());
							if (current > pre) {
								prePersionMap = map;
							}
						}
					}
				}
			}
		}
		System.out.println(prePersionMap);
		return prePersionMap.get("playId").toString();
	}

	@Override
	public boolean isWin() {
		return false;
	}

	@Override
	protected Player next(int index) {
		return null;
	}

	@Override
	public Player nextPlayer(int index) {
		return null;
	}

	@Override
	public TakeCards takecard(Player player, boolean allow, byte[] playCards) {
		return null;
	}

	@Override
	public TakeCards takecard(Player player) {
		return null;
	}

	@Override
	public TakeCards takeCardsRequest(GameRoom gameRoom, Board board, Player player, String orgi, boolean auto,
			byte[] playCards) {
		return null;
	}

	@Override
	public void dealRequest(GameRoom gameRoom, Board board, String orgi, boolean reverse, String nextplayer) {

	}

	@Override
	public void playcards(Board board, GameRoom gameRoom, Player player, String orgi) {

	}

	@Override
	public TakeCards takecard(Player player, TakeCards last) {
		return null;
	}

}
